<?php
function game_go(&$arrReturn)
{
    global $db;
    $speNo = intval($_GET['no']);
    
    if(date( "H" ) < 9) 
    {
    	//取下期时间
    	$sql = "SELECT id,kgtime FROM gamepk10 WHERE kj = 0 AND kgtime > NOW() order by id limit 1";
        $query = $db->query($sql);
        if($rs = $db->fetch_array( $query ))
        {
             $arrRet['nextid'] = $rs['id'];
             $arrRet['nexttime'] = $rs['kgtime'];
        }
        else
        {
			 $sql = "select DATE_ADD(NOW(),INTERVAL 60 SECOND) nowtime";
        	 $query = $db->query($sql);
        	 $rs = $db->fetch_array( $query );
			 $arrRet['nextid'] ='0';
             $arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime($rs["nowtime"]));
        }
    	$arrReturn['msg'] = 'not in open game time(pk)';
    	return;
	}
    
    $No = intval($speNo);
    $arrCatchNo = array();
    if($speNo == 0)
    {
		$sql = "SELECT id FROM gamepk10 WHERE kj = 0 
			 	and id not in(select gameno from game_result where gametype = 'gamepk') AND kgtime < NOW() AND kgtime > DATE_ADD(NOW(),INTERVAL -30 MINUTE )
				ORDER BY id DESC";//
    	$query = $db->query($sql);
    	$i = 0;
    	while($rs = $db->fetch_array( $query ))
    	{
    		$arrCatchNo[$i] = $rs["id"];
    		$i++;
		}

    }
    else
    {
    	
		$sql = "SELECT id FROM gamepk10 WHERE kj = 0 and id = '{$No}' ";
    	$query = $db->query($sql);
    	if($rs = $db->fetch_array( $query ))
    	{
    		$arrCatchNo[0] = $rs["id"];
		}
    	else
    	{
    		$arrReturn['code'] = "ok";
    		$arrReturn['msg'] = "{$No} had opened(pk)";
    		$arrReturn['log'] .= LogFormat("{$No} had opened(pk)");
    		return;
		}
    }
    if(count($arrCatchNo) == 0)
    {
    	 CatchResult($arrCatchNo);
		 $arrReturn['code'] = "ok";
		 $arrReturn['no'] = "0";
    	 $arrReturn['msg'] = "no record to catch(pk)";
    	 $arrReturn['log'] .= LogFormat("no record to catch(pk)");
    	 return;
    }
    $ret = CatchResult($arrCatchNo);
    if ( $ret != "")
    {
		$arrReturn['code'] = "ok";
		$arrRet['nextid'] = "catch_ok";
		$arrReturn['msg'] = "catch_ok";
		$arrReturn['no'] = $ret; 
		$strlog = "catched pk: {$ret},result had been saved(pk)";
    	$arrReturn['log'] .= LogFormat($strlog);
    }
    else //取不到结果
	{
		$ret = implode(',',$arrCatchNo);
		$arrReturn['code'] = 'noreward';
		$arrReturn['no'] = $ret; 
		$arrReturn['msg'] = "can not catch {$ret} result(hg)";
		$arrReturn['log'] = LogFormat("can not catch {$ret} result!(hg)");
	} 
}
function CatchResult($arr)
{
	global $db;
	$ret = "";
	$kjcontent = GetGameResult();
	if(is_array($kjcontent) || strlen($kjcontent) > 0)
	{   
		foreach($arr as $key => $v) 
		{
			$rewardstr = "";
			if(is_array($kjcontent))
			{
				$numberstr = "";
				for($i = 0; $i < count($kjcontent); $i++)
				{
					if($kjcontent[$i]["c_t"] == $v)
					{
						$arrTmp = explode(",",$kjcontent[$i]["c_r"]);
						$numberstr = implode("|",$arrTmp);
						break;
					}
				}
				if(strlen($numberstr) > 0)
				{
					$sql = "call web_savecatch_result('gamepk',{$v},'{$numberstr}')";
					$arrT = $db->Mysqli_Multi_Query($sql);
					$ret .= $v . " ";
				}
			}
			else
			{
				 $kjnum = getbodyc($kjcontent,"<td>{$v}</td>","</td>");
				 $kjnum = trim($kjnum);
				 $arrNum = explode("<td>",$kjnum);
				 if(count($arrNum) > 0)
				 {
					$numberstr = str_replace(",","|",$arrNum[1]);
					if(strlen($numberstr) > 0)
					{
						$sql = "call web_savecatch_result('gamepk',{$v},'{$numberstr}')";
						$arrT = $db->Mysqli_Multi_Query($sql);
						$ret .= $v . " ";
					}
				}
			}
			
		}
	}
	return $ret;
}

function GetGameResult()
{
	$kjNum = GetRameResult_168kai();
	if( !is_array($kjNum))
	$kjNum=GetBeiJingPk10();
	if( !is_array($kjNum) && $kjNum == "")

		$kjNum = GetGameResult_bwlc();

	if( !is_array($kjNum) && $kjNum == "")
		$kjNum = GetGameResult_bjfcdt();
     return $kjNum;
}

function GetRameResult_168kai()
{
	$url = "http://www.168kai.org/Open/CurrentOpen?code=10016&_=" . rand(100000,999999);
	$kjcontent = vita_get_url_content($url);

	$arr = json_decode($kjcontent,true);
	$arrList = $arr['list'];
	return $arrList;
}
function GetBeiJingPk10(){
	$url="http://www.bwlc.net/bulletin/trax.html";
	$html=vita_get_url_content($url);
	preg_match('#<table class="tb"(.*?)</table>#s',$html,$html);
	preg_match_all('#<tr class=".*">\s+<td>(\d+)</td>\s+<td>(.*)</td>\s+<td>(.*)</td>\s+</tr>#',$html[1],$data );
	$result=array();
	foreach ($data[1] as $k=>$v){
		$result[]=array('c_t'=>$v,'c_d'=>$data[3][$k],'c_r'=>$data[2][$k]);
	}
	return $result;
	
}
function vita_get_url_content($url) {
	//if(function_exists('file_get_contents')) {
	//	$file_contents = file_get_contents($url);
	//} else {
		$ch = curl_init();
		$timeout = 5;
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	curl_setopt($ch, CURLOPT_HEADER, 0); //不返回header部分
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串，而非直接输出
	curl_setopt($ch, CURLOPT_COOKIEJAR,  $cookie_file); //存储cookies
		$file_contents = curl_exec($ch);
		if ($file_contents === FALSE) {

			echo "cURL Error: " . curl_error($ch);
		}
		curl_close($ch);
	//}
	return $file_contents;
}
function GetGameResult_bjfcdt()
{
	$kjcontent = fsockurl( "http://tb.bjfcdt.gov.cn/interface.aspx?years=". date('Y-m-d') ."&charttype=PK10other_2" ); 
    $beginText = $theNo . ",[";
    $endText = "]";
    $kjnum = getbodyc( $kjcontent, $beginText, $endText );
    $kjnum = str_replace(",","|",$kjnum);
    return $kjnum;
}

function GetGameResult_bwlc()   
{
	$ret = "";
	$kjcontent = fsockurl("http://www.bwlc.net/bulletin/trax.html");
	$kjnum = getbodyc($kjcontent,"<td>{$theNo}</td>","</td>");
	$kjnum = trim($kjnum);
	$arrNum = explode("<td>",$kjnum);
	if(count($arrNum) > 0)
		$ret = str_replace(",","|",$arrNum[1]);
	return $ret;
} 

error_reporting( 0 );
set_time_limit(200);
include_once( "inc/conn.php" );
include_once( "inc/function.php" );
 
if ( $_GET['key'] == "catch_result_pk" )
{
     $arrRet = array('code'=>'ok', //
    				'no' =>'',
                    'msg'=>'', //错误信息 -1:不在开奖时间内，0：开奖成功，1：该期已开过奖，2：取中奖赔率错误，99：系统错误
                    'log'=>'',
                    'nextid'=>'', //下一盘id
                    'nexttime'=>'' //下一篇开奖时间
        );
    game_go($arrRet);
    if ($arrRet['nextid'] == 'catch_ok')
    {
    	$RandSecond = rand(30,40);
        $sql = "SELECT id,DATE_ADD(kgtime,interval {$RandSecond} second) kgtime FROM gamepk10 WHERE kj = 0 AND kgtime > NOW() limit 1";
        $query = $db->query($sql);
        if($rs = $db->fetch_array( $query ))
        {
             $arrRet['nextid'] = $rs['id'];
             $arrRet['nexttime'] = $rs['kgtime'];
        }
        else
        {
        	 $arrRet['nextid'] ='0';
             $arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime("+{$RandSecond} second"));
        }
    }
    else
    {
		$RandSecond = rand(20,30);
		$sql = "select date_add(NOW(),INTERVAL {$RandSecond} SECOND) nowtime,id from gamepk10 where kgtime > now() and kj = 0 order by id limit 1";
		$query = $db->query($sql);
		if($rs = $db->fetch_array( $query ))
		{
			$arrRet['nextid'] = $rs['id'];
			$arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime($rs["nowtime"]));
		}
		else
		{
			$arrRet['nextid'] ='0';
            $arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime("+{$RandSecond} second"));
		}
    }
    //返回
    echo  json_encode($arrRet);
}
